/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于用户的一些业务逻辑操作
 * @author gcc
 * @date 2014-08-20
 */
package com.chnbst.bstyun.controller.user;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.CreateRandom;
import com.chnbst.bstyun.core.common.DESUtil;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.model.pojo.Area;
import com.chnbst.bstyun.model.pojo.City;
import com.chnbst.bstyun.model.pojo.CompanyIndustry;
import com.chnbst.bstyun.model.pojo.CompanyScale;
import com.chnbst.bstyun.model.pojo.MessageCheck;
import com.chnbst.bstyun.model.pojo.Province;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.service.CompanyIndustryService;
import com.chnbst.bstyun.service.CompanyScaleService;
import com.chnbst.bstyun.service.MessageCheckService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PlaceService;
import com.chnbst.bstyun.service.ShoppingCartService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.mail.EmailUtil;
import com.chnbst.mail.enumeration.MailType;
import com.chnbst.sms.SMSUtil;
import com.chnbst.sms.enumeration.EncodingType;

/**
 * 控制器注解 请求映射注解 controller 代表类是控制器 restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * 
 * @author gcc
 * @date 2014-08-20
 */

@Controller
@RequestMapping("/user")
public class UserController {
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private UserService userService;
	@Autowired
	private MessageCheckService messageCheckService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private PlaceService placeService;
	@Autowired
	private CompanyIndustryService companyIndustryService;
	@Autowired
	private CompanyScaleService companyScaleService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ReadProperties read;
	/**
	 * @return 选择注册方式页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/registerWay", method = RequestMethod.GET)
	public ModelAndView registerWay() throws Exception {
		return new ModelAndView("users/new_register");
	}

	/**
	 * @return 电子邮箱注册页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/registerByEmail", method = RequestMethod.GET)
	public ModelAndView registerByEmail() throws Exception {
		return new ModelAndView("users/registerByEmail");
	}

	/**
	 * @return 手机注册页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/registerByTel", method = RequestMethod.GET)
	public ModelAndView registerByTel() throws Exception {
		return new ModelAndView("users/registerByTel");
	}

	/**
	 * @return 会员中心首页
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/index", method = RequestMethod.GET)
	public ModelAndView userCenter(HttpServletRequest request) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("users/member_center/index/member_index");
		return modelAndView;
	}

	/**
	 * @return 会员信息基本资料
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/basicInfo", method = RequestMethod.GET)
	public ModelAndView userBascInfo(HttpServletRequest request)
			throws Exception {
		User currentUser = (User)request.getSession().getAttribute("userInfo");
		String address = "";
		
		/**
		 * 地区联动相关====================
		 */
		List<Province> provinceList = placeService.getProvinceList();
		Province province = placeService.getProvinceByPcode(currentUser.getProvinceCode());
		City city = placeService.getCityByCcode(currentUser.getCityCode());
		Area area = placeService.getAreaByAcode(currentUser.getAreaCode());
		CompanyIndustry companyIndustry = companyIndustryService.selectCompanyIndustryByCompanyIndustryId(currentUser.getCompanyIndustryId());
		CompanyScale companyScale = companyScaleService.selectCompanyScaleByCompanyScaleId(currentUser.getCompanyScaleId());
		ModelAndView modelAndView = new ModelAndView();
		
		/**
		 * 公司所属行业
		 */
		List<CompanyIndustry> companyIndustries = companyIndustryService.selectCompanyIndustries();
		/**
		 * 公司规模
		 */
		List<CompanyScale> companyScales = companyScaleService.selectCompanyScales();
		modelAndView.addObject("user",currentUser);
		modelAndView.addObject("provinceList",provinceList);
		modelAndView.addObject("province",province);
		modelAndView.addObject("city",city);
		modelAndView.addObject("area", area);
		if(province!=null){
			address+=province.getProvinceName()!=null?province.getProvinceName():"";
		}else {
			address+="";
		}
		if(city!=null){
			address+=city.getCityName()!=null?city.getCityName():"";
		}else {
			address+="";
		}
		if(area!=null){
			address+=area.getAreaName()!=null?area.getAreaName():"";
		}else {
			address+="";
		}
		modelAndView.addObject("detailAddress", address+currentUser.getAddress());
		modelAndView.addObject("companyIndustry", companyIndustry);
		modelAndView.addObject("companyScale",companyScale);
		modelAndView.addObject("companyScales",companyScales);
		modelAndView.addObject("companyIndustries",companyIndustries);
		modelAndView.setViewName("users/member_center/member_information/basic_information");
		return modelAndView;
	}

	/**
	 * @return 会员信息页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/memberInfo", method = RequestMethod.GET)
	public ModelAndView userInfo(HttpServletRequest request) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("requestURI", request.getRequestURI());
		modelAndView.setViewName("users/member_center/member_information/basic_information");
		return modelAndView;
	}

	/**
	 * 进入修改密码页面
	 * @return 修改密码页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/updateMemberPwd", method = RequestMethod.GET)
	public ModelAndView updatePasswordPage() throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("users/member_center/member_information/change_password");
		return modelAndView;
	}

	/**
	 * 进入手机绑定页面
	 * @return 手机绑定页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/boundTel/{flag}", method = RequestMethod.GET)
	public ModelAndView boundTelPage(@PathVariable String flag)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		String temp = "";
		switch (flag) {
		case "telSet":
			temp = "telSet";
			break;
		case "telChange":
			temp = "telChange";
			break;
		case "unBoundEmail":
			temp = "unBoundEmail";
			break;
		default:
			break;
		}
		modelAndView.addObject("flag", temp);
		modelAndView.setViewName("users/member_center/member_information/phone_bound");
		return modelAndView;
	}

	/**
	 * 进入邮箱更换页面
	 * @return 邮箱更换页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/boundEmail/{flag}", method = RequestMethod.GET)
	public ModelAndView boundEmailPage(@PathVariable String flag) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		String temp = "";
		switch (flag) {
		case "emailSet":
			temp = "emailSet";
			break;
		case "emailChange":
			temp = "emailChange";
			break;
		case "unBoundTel":
			temp = "unBoundTel";
			break;
		default:
			break;
		}
		modelAndView.addObject("flag", temp);
		modelAndView.setViewName("users/member_center/member_information/email_bound");
		return modelAndView;
	}

	/**
	 * 会员信息安全信息
	 * 
	 * @return 会员信息安全信息页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/userCenter/memberSafetyInfo", method = RequestMethod.GET)
	public ModelAndView memberSafetyInfo() throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("users/member_center/member_information/safety-information");
		return modelAndView;
	}

	/**
	 * 百顺通云网站服务协议
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/openBstDeal", method = RequestMethod.GET)
	public ModelAndView openBstDeal() throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("users/bstdeal");
		return modelAndView;
	}

	/**
	 * 百顺通云网站服务协议（普元帐号登录）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/py/openBstDeal", method = RequestMethod.GET)
	public ModelAndView openBstDealForPY() throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("users/py_login_deal");
		return modelAndView;
	}
	
	/**
	 * @return 登录页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView LoginAuthenticator(HttpServletRequest request)
			throws Exception {
		String returnUrl = request.getParameter("returnUrl");
		ModelAndView mav = new ModelAndView();
		mav.addObject("returnUrl", returnUrl);
		mav.setViewName("users/new_login");
		return mav;
	}

	/**
	 * @return 用户忘记密码页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
	public ModelAndView forGetPassword() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("users/forget_password");
		return mav;
	}

	/**
	 * get请求 显示单个用户详细页面
	 */
	@RequestMapping(value = "/exit", method = RequestMethod.GET)
	public ModelAndView userExit(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.getSession().invalidate();
		ModelAndView object = new ModelAndView();
		Cookie[] cookies=request.getCookies(); 
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("userName")){
				cookie.setMaxAge(0); 
				cookie.setPath("/");
			    response.addCookie(cookie); 
			}
			if(cookie.getName().equals("userPassword")){
				cookie.setMaxAge(0);
				cookie.setPath("/");
			    response.addCookie(cookie);
			}
		}
		object.setViewName("redirect:/");
		return object;
	}

	/**
	 * 核对图片验证码是否正确
	 * @return 验证信息，true:验证码正确 false:验证码错误
	 */
	@RequestMapping(value = "/checkImgCode", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkImgCode(String imageCode, HttpServletRequest request)
			throws Exception {
		boolean success = false;
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute("code");
		if (code != null && code != "") {
			if (code.equalsIgnoreCase(imageCode)) {
				success = true;
			} else {
				success = false;
			}
		}
		return success;
	}

	/**
	 * post请求 ajax 执行添加用户
	 * @param user
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> save(HttpServletRequest request)
			throws Exception {
		String messageCode = "";
		HttpSession session = request.getSession();
		String msgCode = request.getParameter("vftn_code");
		String phone = request.getParameter("phone");
		String psd = request.getParameter("psd");
		String email = request.getParameter("email");
		messageCode = (String) session.getAttribute("messageCode");
		Map<String, Object> map = new HashMap<String, Object>();
		if (phone != null&&!phone.equals("")) {// 手机方式注册
				if (!msgCode.equals(messageCode)) {
					map.put("messageCode", false);
				} else {
					map.put("messageCode", true);
						User user = new User();
						String md5Password = DESUtil.encrypt(psd);
						user.setUserEmail(email);
						user.setUserTel(phone);
						user.setUserPassword(md5Password);
						user.setUserValid("0");
						user.setLastLoginTime(new Date());
						user.setAccountMoney(0.00);
						user.setInvoiceMoney(0.00);
						user.setApprove("1");
						user.setUserMessageNum(0);
						user.setAddTime(new Date());
						user.setBoundTel(phone);
						user.setIsLive("1");
						user.setIsYun("1");
						boolean success = userService.insertUser(user);
						map.put("saveSuccess", success);
						if (success == true) {
							session.setAttribute("loginWay", "tel");
							session.setAttribute("userInfo", user);
						}
//					}
				}
		} else {// email方式
			map.put("email", email);
			map.put("emailCode", true);
			map.put("messageCode", true);
			map.put("imgSuccess", true);
			map.put("saveSuccess", true);
//			Properties props = new Properties();
//			InputStream fileInputStream = request.getSession().getServletContext().getResourceAsStream("/WEB-INF/config/bstyunUrl.properties");
//			InputStream in = new BufferedInputStream(fileInputStream);
//			props.load(in);
			//String value = props.getProperty("URL");
			String value = read.getUrl();
			String url = value+"/user/acceptActivateEmail?email="+email;
			boolean success = sendActivateEmail(email,url);
			map.put("sendSuccess", success);
		}

		return map;
	}

	/**
	 * post请求 ajax 执行查询用户
	 * @param boundEmail
	 * @return 布尔值 true:用户不存在 false:用户存在
	 */
	@RequestMapping(value = "/bound/boundEmail", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserByBoundEmail(String boundEmail) throws Exception {
		boolean success = true;
		User user = (User)userService.boundEmailExists(boundEmail);
		if (user != null) {
			success = false;
		}
		return success;
	}

	/**
	 * post 请求 执行查询用户
	 * @param userTel
	 * @return 布尔值 true:用户不存在 false:用户存在
	 * @throws Exception
	 */
	@RequestMapping(value = "/bound/boundTel", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserByBoundTel(String boundTel) throws Exception {
		boolean success = false;
		User user = (User) userService.selectUserPsdByBoundTel(boundTel);
		if (user == null) {
			success = true;
		}
		return success;
	}

	/**
	 * post 请求 执行查询用户
	 * @param boundTel
	 * @return 布尔值 true:用户不存在 false:用户存在
	 * @throws Exception
	 */
	@RequestMapping(value = "/bound/selectUserPsdByBoundTel", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserPsdByBoundTel(String boundTel) throws Exception {
		boolean success = false;
		User user = (User) userService.selectUserPsdByBoundTel(boundTel);
		if (user == null) {
			success = true;
		}
		return success;
	}
	
	/**
	 * post 请求 执行查询用户
	 * @param boundTel
	 * @return 布尔值 true:用户不存在 false:用户存在
	 * @throws Exception
	 */
	@RequestMapping(value = "/bound/selectUserPsdByBoundEmail", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserPsdByBoundEmail(String boundEmail) throws Exception {
		boolean success = false;
		User user = (User) userService.selectUserPsdByBoundEmail(boundEmail);
		if (user == null) {
			success = true;
		}
		return success;
	}
	/**
	 * post请求 ajax 执行查询用户
	 * @param Email
	 * @return 布尔值 true:用户不存在 false:用户存在
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/email", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserByEmail(String userEmail) throws Exception {
		boolean success = true;
		List<User> user = (List<User>)userService.emailExists(userEmail);
		if (user != null&&!user.isEmpty()) {
			success = false;
		}
		return success;
	}

	/**
	 * post 请求 执行查询用户
	 * @param userTel
	 * @return 布尔值 true:用户不存在 false:用户存在
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/tel", method = RequestMethod.POST)
	@ResponseBody
	public boolean selectUserByTel(String userTel) throws Exception {
		boolean success = true;
		List<User> user = (List<User>)userService.TelExists(userTel);
		if (user != null&&!user.isEmpty()) {
			success = false;
		}
		return success;
	}

	/**
	 * 更新用户
	 * @param account,password  邮箱或则手机号,密码
	 * @return
	 */
	@RequestMapping(value = "/update/password", method = RequestMethod.POST)
	@ResponseBody
	public boolean UpdateUserByAccount(String account, String password)
			throws Exception {
		boolean flag = false;
		boolean tempFlag;
		User user = new User();
		if (password == null) {
			password = "12345678";
		}
		Integer temp = account.indexOf("@");
		if (temp == -1) {
			String success = SMSUtil.sendMessage(new String[] { account },
					"MB-2014090506", new String[] { password },
					EncodingType.UTF8, null);
			if (success.indexOf("发送成功") != -1) {
				tempFlag = true;
				user.setBoundTel(account);
			} else {
				tempFlag = false;
			}
		} else {
			User currentUser = (User)userService.boundEmailExists(account);
			tempFlag = EmailUtil.sendMail(MailType.GET_PASSWORD_BACK, null, account, null, password, currentUser.getUserEmail(), null);
			user.setBoundEmail(account);
		}
		String newPassword = DESUtil.encrypt(password);
		user.setUserPassword(newPassword);
		if (tempFlag) {
			userService.findPassword(user);
			flag = true;
		} else {
			flag = false;
		}
		return flag;
	}

	/**
	 * 用户修改密码
	 * @param password 密码
	 * @return true：更新成功  false:更新失败
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public boolean updatePassword(String password, HttpServletRequest request)
			throws Exception {
		User userInfo = (User) request.getSession().getAttribute("userInfo");
		String userEmail = userInfo.getUserEmail();
		String userTel = userInfo.getUserTel();
		User user = new User();
//		if (userEmail == null||userEmail.e) {
//			user.setUserTel(userTel);
//		} else {
//			user.setUserEmail(userEmail);
//		}
		if(userEmail!=null&&!"".equals(userEmail)){
			user.setUserEmail(userEmail);
		}else {
			user.setUserTel(userTel);
		}
		
		String newPassword = DESUtil.encrypt(password);
		user.setUserPassword(newPassword);
		return userService.updateUserByAccount(user);
	}

	/**
	 * 用户忘记密码页面找回密码
	 * @param account,imageCode,request
	 * @return 0:验证码错误 1：密码更新失败 2：密码更新成功
	 */
	@RequestMapping(value = "/findPassword", method = RequestMethod.POST)
	@ResponseBody
	public String findPassword(String account, String imageCode,
			HttpServletRequest request) throws Exception {
		boolean checkImgCode = checkImgCode(imageCode, request);
		String flag = ""; // 0:验证码错误 1：密码更新失败 2：邮件方式找回密码成功；3：手机方式找回密码成功
		if (checkImgCode) {
			boolean success = UpdateUserByAccount(account, null);
			if (success) {
				if(account.indexOf("@")==-1){
					flag = "3";
				}else {
					flag = "2";
				}
			} else {
				flag = "1";
			}
		} else {
			flag = "0";
		}
		return flag;
	}

	/**
	 * 用户注册获取短信验证码
	 * @param tel
	 * @return 布尔值 true:发送成功 false:发送失败
	 */
	@RequestMapping(value = "/getMsgCode", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getMsgCode(String tel, HttpServletRequest request)
			throws Exception {
		String message = null;
		String getMsgCode = CreateRandom.createRandom(true, 6);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date currentDate = new Date();
		MessageCheck messageCheck = new MessageCheck();
		Map<String, Object> map = new HashMap<String, Object>();
		messageCheck.setToTel(tel);
		messageCheck = messageCheckService.selectByToTel(messageCheck);
		if (messageCheck == null) {
			String success = SMSUtil.sendMessage(new String[] { tel },
					"MB-2014090144", new String[] { getMsgCode },
					EncodingType.UTF8, null);
			if (success.indexOf("发送成功") != -1) {
				request.getSession().setAttribute("messageCode", getMsgCode);
				MessageCheck messageCheck2 = new MessageCheck();
				messageCheck2.setToTel(tel);
				messageCheck2.setSendTime(currentDate);
				messageCheck2.setSendNum(1);
				messageCheckService.insertMessageInfo(messageCheck2);
				message = "发送成功";
			} else {
				message = "发送失败";
			}
		} else {
			Integer sendNum = messageCheck.getSendNum();
			Date senDate = messageCheck.getSendTime();
			String date = format.format(senDate);
			String currentTime = format.format(currentDate);
			if (sendNum < 3) {
				if (date.equals(currentTime)) {
					String success = SMSUtil.sendMessage(new String[] { tel },
							"MB-2014090144", new String[] { getMsgCode },
							EncodingType.UTF8, null);
					if (success.indexOf("发送成功") != -1) {
						request.getSession().setAttribute("messageCode",
								getMsgCode);
						messageCheck.setToTel(tel);
						messageCheck.setSendNum(messageCheck.getSendNum() + 1);
						messageCheckService.updateByToTel(messageCheck);
						message = "发送成功";
					} else {
						message = "发送失败";
					}
				} else {
					String success = SMSUtil.sendMessage(new String[] { tel },
							"MB-2014090144", new String[] { getMsgCode },
							EncodingType.UTF8, null);
					if (success.indexOf("发送成功") != -1) {
						request.getSession().setAttribute("messageCode",
								getMsgCode);
						messageCheck.setToTel(tel);
						messageCheck.setSendTime(currentDate);
						messageCheck.setSendNum(1);
						messageCheckService.updateByToTel(messageCheck);
						message = "发送成功";
					} else {
						message = "发送失败";
					}

				}

			} else {
				if (!date.equals(currentTime)) {
					String success = SMSUtil.sendMessage(new String[] { tel },
							"MB-2014090144", new String[] { getMsgCode },
							EncodingType.UTF8, null);
					if (success.indexOf("发送成功") != -1) {
						request.getSession().setAttribute("messageCode",
								getMsgCode);
						messageCheck.setToTel(tel);
						messageCheck.setSendTime(currentDate);
						messageCheck.setSendNum(1);
						messageCheckService.updateByToTel(messageCheck);
						message = "发送成功";
					} else {
						message = "发送失败";
					}

				} else {
					message = "每天最多只能发送三次";
				}
			}
		}
		map.put("message", message);
		return map;
	}

	/**
	 * 根据帐号发送邮件或短信
	 * @param account
	 * @param flag bound:绑定  unBound:解绑
	 * @return true：成功 false：失败
	 */
	@RequestMapping(value="/sendInfoByAccount",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> sendInfoByAccount(String account,String flag,HttpServletRequest request) throws Exception{
		Integer temp = account.indexOf("@");
		String getCheckCode = CreateRandom.createRandom(true, 6);
		request.getSession().setAttribute("messageCode", getCheckCode);
		Map<String, Object> map = new HashMap<String, Object>();
		if(temp==-1){
			/*发送短信 0:发送成功 1：发送失败 2：每天最多只能发送3次*/
			MessageCheck messageCheck = new MessageCheck();
			messageCheck.setToTel(account);
			messageCheck = messageCheckService.selectByToTel(messageCheck);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date currentDate = new Date();
			if(messageCheck==null){
				if(flag.equals("bound")){//绑定手机
					String success = SMSUtil.sendMessage(new String[] { account },
							"MB-2014091931", new String[] { getCheckCode },
							EncodingType.UTF8, null);
					if (success.indexOf("发送成功") != -1) {
						MessageCheck messageCheck2 = new MessageCheck();
						messageCheck2.setToTel(account);
						messageCheck2.setSendTime(currentDate);
						messageCheck2.setSendNum(1);
						messageCheckService.insertMessageInfo(messageCheck2);
						map.put("flag", "0");
					}else{
						map.put("flag", "1");
					}
				}else{//解绑邮箱
					String success = SMSUtil.sendMessage(new String[] { account },
							"MB-2014091907", new String[] { getCheckCode },
							EncodingType.UTF8, null);
					if (success.indexOf("发送成功") != -1) {
						MessageCheck messageCheck2 = new MessageCheck();
						messageCheck2.setToTel(account);
						messageCheck2.setSendTime(currentDate);
						messageCheck2.setSendNum(1);
						messageCheckService.insertMessageInfo(messageCheck2);
						map.put("flag", "0");
					}else{
						map.put("flag", "1");
					}
				}
				
			
			}else {
				Integer sendNum = messageCheck.getSendNum();
				Date senDate = messageCheck.getSendTime();
				String date = format.format(senDate);
				String currentTime = format.format(currentDate);
				if(flag.equals("bound")){//绑定手机
					if (sendNum<3) {
						if (date.equals(currentTime)) {
							String success = SMSUtil.sendMessage(new String[] { account },
									"MB-2014091931", new String[] { getCheckCode },
									EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",
										getCheckCode);
								messageCheck.setSendNum(messageCheck.getSendNum() + 1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}
						} else {
							String success = SMSUtil.sendMessage(new String[] { account },
									"MB-2014091931", new String[] { getCheckCode },
									EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",
										getCheckCode);
								messageCheck.setSendTime(currentDate);
								messageCheck.setSendNum(1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}

						}
					}else {
						if (!date.equals(currentTime)) {
							String success = SMSUtil.sendMessage(new String[] { account },
									"MB-2014091931", new String[] { getCheckCode },
									EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",getCheckCode);
								messageCheck.setSendTime(currentDate);
								messageCheck.setSendNum(1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}
						} else {
							map.put("flag", "2");
						}
					}
				}else{//解绑邮箱
					if (sendNum<3) {
						if (date.equals(currentTime)) {
							String success = SMSUtil.sendMessage(new String[] { account },"MB-2014091907", new String[] { getCheckCode },EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",getCheckCode);
								messageCheck.setSendNum(messageCheck.getSendNum() + 1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}
						} else {
							String success = SMSUtil.sendMessage(new String[] { account },
									"MB-2014091907", new String[] { getCheckCode },
									EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",getCheckCode);
								messageCheck.setSendTime(currentDate);
								messageCheck.setSendNum(1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}
						}
					}else {
						if (!date.equals(currentTime)) {
							String success = SMSUtil.sendMessage(new String[] { account },
									"MB-2014091907", new String[] { getCheckCode },
									EncodingType.UTF8, null);
							if (success.indexOf("发送成功") != -1) {
								request.getSession().setAttribute("messageCode",getCheckCode);
								messageCheck.setSendTime(currentDate);
								messageCheck.setSendNum(1);
								messageCheckService.updateByToTel(messageCheck);
								map.put("flag", "0");
							} else {
								map.put("flag", "1");
							}
						} else {
							map.put("flag", "2");
						}
					}
				}
			}
		}else {
			//发送邮件
			User user = (User)request.getSession().getAttribute("userInfo");
			String userName = "";
			if (account.indexOf("@")==-1) {
				userName = user.getUserTel();
			}else {
				userName = user.getUserEmail();
			}
			if(flag.equals("bound")){//绑定邮箱
				boolean tempFlag = EmailUtil.sendMail(MailType.BIND_MAIL, null, account, null, null, userName, getCheckCode);
				if (tempFlag) {
					map.put("flag", "0");
				}else{
					map.put("flag", "1");
				}
			}else {//解绑手机
				boolean tempFlag = EmailUtil.sendMail(MailType.UNBIND_TELEPHONE, null, account, null, null, userName, getCheckCode);
				if (tempFlag) {
					map.put("flag", "0");
				}else{
					map.put("flag", "1");
				}
			}
			
		
		}
		return map;
	}
	/**
	 * ajax请求查询用户帐号密码
	 * @param userEmail
	 * @param userPassword
	 * @return
	 */
	@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> loginCheck(String userEmail, String userPassword)
			throws Exception {
		Integer temp = userEmail.indexOf("@");
		Map<String, Object> map = new HashMap<String, Object>();
		User user = new User();
		if (temp == -1) {
			user.setUserTel(userEmail);
			User loginUser = (User) userService.selectUserByAccount(user);
			if (loginUser != null) {
				String newPassword = DESUtil.encrypt(userPassword);
				if (newPassword.equals(loginUser.getUserPassword())) {
					map.put("loginMessage", "success");
				} else {
					map.put("loginMessage", "密码不正确");
				}
			} else {
				map.put("loginMessage", "帐号不存在");
			}
		} else {
			User loginUser = new User();
			loginUser.setUserEmail(userEmail);
			loginUser = (User)userService.selectUserByAccount(loginUser);
			if (loginUser != null) {
				String newPassword = DESUtil.encrypt(userPassword);
				if (newPassword.equals(loginUser.getUserPassword())) {
					if(loginUser.getIsLive().equals("1")){
						if(loginUser.getIsYun().equals("1")){
							map.put("isyun", "yes");
							map.put("loginMessage", "success");
						}else {
							map.put("isyun", "no");
							map.put("loginMessage", "success");
							String loginNumber = loginUser.getLoginNumber();
							if(loginNumber.equals("0")){
								map.put("isFirstLogin", "yes");
							}
						}
					}else{
						map.put("loginMessage", "无效用户");
					}
				} else {
					map.put("loginMessage", "密码不正确");
				}
			} else {
				map.put("loginMessage", "帐号不存在");
			}
		}
		return map;
	}

	/**
	 * 用户登录
	 * @param user
	 * @param request
	 * @return 登录成功页面
	 */
	@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
	public ModelAndView login(User user, HttpServletRequest request,HttpServletResponse response)
			throws Exception {
		String returnUrl = request.getParameter("returnUrl");
		String isFirstLogin = request.getParameter("isFirstLogin");
		String userEmail = user.getUserEmail();
		String userPassword = user.getUserPassword();
		String loginAuto = request.getParameter("loginAuto");
		ModelAndView mav = new ModelAndView();
		Integer temp = userEmail.indexOf("@");
		if (temp == -1) {
			user = new User();
			user.setUserTel(userEmail);
			User loginUser = (User)userService.selectUserByAccount(user);
			String newPassword = DESUtil.encrypt(userPassword);
			if (newPassword.equals(loginUser.getUserPassword())) {
				if (loginAuto.equals("true")) {
					String userTel = loginUser.getUserTel();
					String newUserEmail = loginUser.getUserEmail();
					String account = null;
					if(userTel!=null&&!userTel.equals("")){
						account = loginUser.getUserTel();
					}
					if(newUserEmail!=null&&!newUserEmail.equals("")){
						account = loginUser.getUserEmail();
					}
					Cookie cookieUserName = new Cookie("userName", account);
					cookieUserName.setPath("/");
					cookieUserName.setMaxAge(14*24*60*60);
					response.addCookie(cookieUserName);
					Cookie cookiePwd = new Cookie("userPassword", loginUser.getUserPassword());
					cookiePwd.setPath("/");
					cookiePwd.setMaxAge(14*24*60*60);
					response.addCookie(cookiePwd);
					
				}
				request.getSession().setAttribute("userInfo", loginUser);
				String userTel = loginUser.getUserTel();
				String newUserEmail = loginUser.getUserEmail();
				if(userTel!=null&&!userTel.equals("")){
					request.getSession().setAttribute("loginWay", "tel");
				}
				if(newUserEmail!=null&&!newUserEmail.equals("")){
					request.getSession().setAttribute("loginWay", "email");
				}
				
				Map<String, Object> cartInfo = shoppingCartService.selectShoppingCartCountByUserId(loginUser.getUserId());
				if(cartInfo.get("sumPrice") == null) cartInfo.put("sumPrice", 0.0);
				request.getSession().setAttribute("cartInfo", cartInfo);
				
				if (SignUtil.isEmpty(returnUrl)) {
					mav.setViewName("redirect:/");
				} else {
					mav.setViewName("redirect:" + returnUrl);
				}
				User newUser = new User();
				newUser.setUserId(loginUser.getUserId());
				newUser.setLastLoginTime(new Date());
				userService.updateUserLastTime(newUser);

			}
		} else {
			user = new User();
			user.setUserEmail(userEmail);
			User loginUser = (User)userService.selectUserByAccount(user);
			String newPassword = DESUtil.encrypt(userPassword);
			if (newPassword.equals(loginUser.getUserPassword())) {
				if(isFirstLogin.equals("yes")){
					String loginNumber = loginUser.getLoginNumber();
					if(loginNumber.equals("0")){
						User newUser = new User();
						newUser.setUserId(loginUser.getUserId());
						newUser.setLoginNumber("1");
						userService.updateUserByKey(newUser);
					}
				}
				if (loginAuto.equals("true")) {
					String userTel = loginUser.getUserTel();
					String newUserEmail = loginUser.getUserEmail();
					String account = null;
					if(userTel!=null&&!userTel.equals("")){
						account = loginUser.getUserTel();
					}
					if(newUserEmail!=null&&!newUserEmail.equals("")){
						account = loginUser.getUserEmail();
					}
					Cookie cookieUserName = new Cookie("userName", account);
					cookieUserName.setPath("/");
					cookieUserName.setMaxAge(14*24*60*60);
					response.addCookie(cookieUserName);
					Cookie cookiePwd = new Cookie("userPassword", loginUser.getUserPassword());
					cookiePwd.setPath("/");
					cookiePwd.setMaxAge(14*24*60*60);
					response.addCookie(cookiePwd);
					
				}
				request.getSession().setAttribute("userInfo", loginUser);
				String userTel = loginUser.getUserTel();
				String newUserEmail = loginUser.getUserEmail();
				if(userTel!=null&&!userTel.equals("")){
					request.getSession().setAttribute("loginWay", "tel");
				}
				if(newUserEmail!=null&&!newUserEmail.equals("")){
					request.getSession().setAttribute("loginWay", "email");
				}
				
				Map<String, Object> cartInfo = shoppingCartService.selectShoppingCartCountByUserId(loginUser.getUserId());
				if(cartInfo.get("sumPrice") == null) cartInfo.put("sumPrice", 0.0);
				request.getSession().setAttribute("cartInfo", cartInfo);
				
				if (SignUtil.isEmpty(returnUrl)) {
					mav.setViewName("redirect:/");
				} else {
					mav.setViewName("redirect:" + returnUrl);
				}
			}
			// 用户登录信息表中更新用户的上次登录时间
			User newUser = new User();
			newUser.setUserId(loginUser.getUserId());
			newUser.setLastLoginTime(new Date());
			userService.updateUserLastTime(newUser);

		}
		return mav;
	}

	/**
	 * 校验原密码是否正确
	 * @param password
	 * @return true:正确 false:错误
	 */
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	@ResponseBody
	public boolean changePassword(String password, HttpServletRequest request)
			throws Exception {
		String oldPassword = "";
		User user = (User) request.getSession().getAttribute("userInfo");
		if (user.getUserEmail() != null && !user.getUserEmail().equals("")) {
			User object = (User) userService.selectUserByAccount(user);
			oldPassword = object.getUserPassword();
		} else {
			User object = (User) userService.selectUserByAccount(user);
			oldPassword = object.getUserPassword();
		}
		String newPassword = DESUtil.encrypt(password);
		if (oldPassword.equals(newPassword)) {
			return true;
		}
		return false;
	}

	/**
	 * 根据登录帐号绑定手机或email
	 * @param account
	 * @param request
	 * @return true:绑定成功 false:绑定失败
	 * @throws Exception
	 */
	@RequestMapping(value = "/safeInfoBound", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> safeInfoBound(HttpServletRequest request)
			throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("userInfo");
		String account = request.getParameter("account");
		String messageCode = request.getParameter("messageCode");
		String emailFlag = request.getParameter("emailFlag");
		Map<String, Object> map = new HashMap<String, Object>();
		//0:验证码错误 1：绑定成功 2：绑定失败
		String msgCode = (String)session.getAttribute("messageCode");
		if(!messageCode.equals(msgCode)){
			map.put("message", "0");
		}else {
			if (account.indexOf("@") == -1) {
				if (emailFlag.equals("unBoundEmail")){
					user.setBoundEmail(null);
					boolean success = userService.updateUserSafeInfo(user);
					if(success){
						session.setAttribute("userInfo",user );
						map.put("message", "1");
					}else {
						map.put("message", "2");
					}
				}else {
					user.setBoundTel(account);
					boolean success = userService.updateUserByKey(user);
					if(success){
						session.setAttribute("userInfo",user );
						map.put("message", "1");
					}else {
						map.put("message", "2");
					}
				}
			} else {
				if (emailFlag.equals("unBoundTel")) {
					user.setBoundTel(null);
					boolean flag =userService.updateUserSafeInfo(user);
					if(flag){
						session.setAttribute("userInfo",user );
						map.put("message", "1");
					}else {
						map.put("message", "2");
					}
				}else {
					user.setBoundEmail(account);
					boolean success = userService.updateUserByKey(user);
					if(success){
						session.setAttribute("userInfo",user );
						map.put("message", "1");
					}else {
						map.put("message", "2");
					}
				}
			}
		}
		return map;
	}
	
	/**
	 * 更新用户基本资料
	 * @param User
	 * @param request
	 * @return true:更新成功   false:更新失败
	 */
	@RequestMapping(value="/userCenter/update/basicInfo",method=RequestMethod.POST)
	@ResponseBody
	public boolean updateUserForPerson(HttpServletRequest request) throws Exception{
		SimpleDateFormat time = new SimpleDateFormat("yyy-MM-dd");
		HttpSession session = request.getSession();
		User currentUser = (User)session.getAttribute("userInfo");
		String realName = request.getParameter("realName");
		String sex = request.getParameter("sex");
		Date birthday = request.getParameter("birthday")==""?null:time.parse(request.getParameter("birthday"));
		String phone = request.getParameter("phone");
		String fixationTel = request.getParameter("fixationTel");
		String personEmail = request.getParameter("personEmail");
		String fax = request.getParameter("fax");
		Integer provinceCode = request.getParameter("provinceCode")==""?null:Integer.valueOf(request.getParameter("provinceCode"));
		Integer cityCode = request.getParameter("cityCode")==""?null:Integer.valueOf(request.getParameter("cityCode"));
		Integer areaCode = request.getParameter("areaCode")==""?null:Integer.valueOf(request.getParameter("areaCode"));
		String address = request.getParameter("address");
		String belongCompanyName = request.getParameter("belongCompanyName");
		Integer companyIndustryId = request.getParameter("companyIndustryId")==""?null:Integer.valueOf(request.getParameter("companyIndustryId"));
		Integer companyScaleId = request.getParameter("companyScaleId")==""?null:Integer.valueOf(request.getParameter("companyScaleId"));
		String companyPosition = request.getParameter("companyPosition");
		User user = new User();
		user = userService.selectUserInfoByUserId(currentUser.getUserId());
		user.setUserId(currentUser.getUserId());
		user.setAddress(address);
		user.setBelongCompanyName(belongCompanyName);
		user.setBirthday(birthday);
		user.setCityCode(cityCode);
		user.setAreaCode(areaCode);
		user.setCompanyIndustryId(companyIndustryId);
		user.setCompanyPosition(companyPosition);
		user.setCompanyScaleId(companyScaleId);
		user.setFax(fax);
		user.setRealName(realName);
		user.setSex(sex);
		user.setPhone(phone);
		user.setFixationTel(fixationTel);
		user.setPersonEmail(personEmail);
		user.setProvinceCode(provinceCode);
		boolean success = userService.updateUserByUserId(user);
		if (success) {
			session.setAttribute("userInfo", user);
			return true;
		}else {
			return false;
		}
	}


	/**
	 * 发送邮件（验证码）
	 * @param email
	 * @param request
	 * @return true:成功  false:失败
	 */
	@RequestMapping(value="/sendEmail",method=RequestMethod.POST)
	@ResponseBody
	public boolean sendEmail(String email,HttpServletRequest request)throws Exception{
		String getCheckCode = CreateRandom.createRandom(true, 6);
		request.getSession().setAttribute("messageCode", getCheckCode);
		boolean success = EmailUtil.sendMail(MailType.REGISTER_MAIL, "", email, null, "", "", getCheckCode);
		if(success){
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * 发送邮件（注册激活）
	 * @param email
	 * @return true:成功  false:失败
	 */
	public boolean sendActivateEmail(String email,String url)throws Exception{
		boolean success = EmailUtil.sendMailRegister(email, url);
		if(success){
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * 接受激活邮件跳转邮件注册页面
	 * @param request
	 * @return 邮件注册页面
	 */
	@RequestMapping(value="/acceptActivateEmail",method=RequestMethod.GET)
	public ModelAndView acceptActivateEmail(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView();
		String email = request.getParameter("email");
		mav.addObject("email", email);
		mav.setViewName("users/new_registerByEmail");
		return mav; 
	}
	
	/**
	 * 通过Email注册用户
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/saveUserByEmail",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUserByEmail(HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		String email = request.getParameter("email");
		String psd = request.getParameter("psd");
		String picode = request.getParameter("picode");
		String imgageCode = (String)session.getAttribute("code");
		Map<String, Object> map = new HashMap<String, Object>();
		if (!imgageCode.equalsIgnoreCase(picode)) {
			map.put("errorInfo","验证码不正确");
		}else {
			map.put("errorInfo","验证码正确");
			User user = new User();
			String md5Password = DESUtil.encrypt(psd);
			user.setUserEmail(email);
			user.setUserPassword(md5Password);
			user.setUserValid("0");
			user.setLastLoginTime(new Date());
			user.setAccountMoney(0.00);
			user.setInvoiceMoney(0.00);
			user.setApprove("1");
			user.setUserMessageNum(0);
			user.setAddTime(new Date());
			user.setBoundEmail(email);
			user.setIsLive("1");
			user.setIsYun("1");
			boolean success = userService.insertUser(user);
			map.put("saveSuccess", success);
			if (success == true) {
				session.setAttribute("loginWay", "email");
				session.setAttribute("userInfo", user);
			}
		}
		return map;
	}
}
